package com.crl.rcdp.sys.dao;

import com.cars.util.page.PageUtil;
import com.cars.util.string.StringUtil;
import com.crl.dao.BaseDao;
import com.crl.rcdp.sys.model.SysLog;
import com.crl.rcdp.sys.vo.SysLogSearchVO;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/6/22 11:10
 */
@Repository
public class SysLogDao extends BaseDao<SysLog, SysLogSearchVO> {
    /**
     * 根据条件统计总数
     */
    public int count(SysLogSearchVO sysLogSearchVO) {
        String sql = "SELECT COUNT(*) FROM td_sys_log WHERE 1=1 ";
        sql += createSQL(sysLogSearchVO);
        return count(sql, sysLogSearchVO);
    }

    private String createSQL(SysLogSearchVO sysLogSearchVO) {
        String sql = "";
        if (StringUtil.isNotNullOrEmpty(sysLogSearchVO.getOwner())) {
            sql += " and owner = :owner";
        }

        if (StringUtil.isNotNullOrEmpty(sysLogSearchVO.getStartDate())) {
            sql += " and request_date >=date(:startDate) ";
        }

        //截止日期默认当前选中的加一天
        if (StringUtil.isNotNullOrEmpty(sysLogSearchVO.getEndDate())) {
            sql += " and request_date <=date_add(:endDate,interval 1 day) ";
        }

        return sql;
    }

    /**
     * 根据条件查询日志列表
     *
     * @param sysLogSearchVO
     * @return
     */
    public List<SysLog> list(SysLogSearchVO sysLogSearchVO) {
        String sql = "select * from td_sys_log where 1=1";
        sql += createSQL(sysLogSearchVO);
        sql+=" order by request_date desc";
        sql = PageUtil.createMysqlPageSql(sql, sysLogSearchVO.getPage());
        return list(sql, sysLogSearchVO);
    }

    /**
     * 请求日志入库
     *
     * @param sysLog 日志信息
     * @return 日志入库情况
     */
    public int add(SysLog sysLog) {
        String sql = "insert into td_sys_log (owner, auth_type, request_date, path, service_name, request_param, client_ip)" +
                " values (:owner, :authType, now(), :path, :serviceName, :requestParam, :clientIp)";
        return insertForId(sql, sysLog, "id");
    }

    public int update(SysLog sysLog) {
        String sql = "update td_sys_log set  time_consuming=:timeConsuming,response=:response where id=:id";
        return update(sql, sysLog);
    }
}